package 力扣;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 示例 1：
 输入：nums = [1,1,2]
 输出：
 [[1,1,2],
 [1,2,1],
 [2,1,1]]
 示例 2：
 输入：nums = [1,2,3]
 输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 */

public class _47全排列II {


    public List<List<Integer>> permuteUnique(int[] nums) {
        //回溯法
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        Set<List<Integer>> set = new HashSet<>();
        List<Integer> permuteList= new ArrayList<Integer>();
        boolean[] visited = new boolean[nums.length];
        backtracking(visited,nums,permuteList,set);
        for(List list: set){
            ret.add(list);
        }
        return ret;
    }

    private void backtracking(boolean[] visited, int[] nums, List<Integer> permuteList, Set<List<Integer>>  set) {
        if( nums.length == permuteList.size()){
            set.add(new ArrayList<>(permuteList));
            return;
        }
        for (int i = 0; i < nums.length ; i++) {
            if( visited[i]) continue;
            permuteList.add(nums[i]);
            visited[i] = true;
            backtracking(visited,nums,permuteList,set);
            visited[i] = false;
            permuteList.remove(permuteList.size()-1);
        }
    }


}
